package com.fs.system.security;

import com.alibaba.fastjson2.JSON;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.vo.AjaxResult;
import com.fs.common.core.vo.LoginUser;
import com.fs.common.util.ServletUtils;
import com.fs.system.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author suke
 * @version 1.0
 * @title LogoutSuccessHandlerImpl
 * @description 注销成功的处理器
 * @create 2024/7/26 15:19
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //1.根据token获取redis的存储的LoginUser对象
        LoginUser loginUser = tokenService.getLoginUser(request);
        //2.判断LoginUser是否为空, 不为空,  删除redis的LoginUser,
        if(Objects.nonNull(loginUser)){
            //删除redis中LoginUser
            tokenService.delLoginUser(loginUser.getToken());
        }
        //3.响应注销成功的json
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("注销成功")));
    }
}
